package com.student.controller;


import com.student.model.Student;
import com.student.model.StudentDAO;
import com.student.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired                      //依赖注入，把数据库引入进来，把DAO对象拉过来
    private StudentDAO studentDAO;

    @Autowired
    private UserService userService;  //把service层注入


    @PostMapping("/signUp")    //学生账号注册(添加学生)
    public ResponseEntity</*Student*/ ?> register(@RequestBody Student student){
        if(studentDAO.existsBySerialNumber(student.getSerialNumber())) {
            return new ResponseEntity<>("该学生已注册", HttpStatus.BAD_REQUEST);//参数有误
        }else{
            return new ResponseEntity<Student>(studentDAO.save(student),HttpStatus.OK);   //成功注册一个学生
        }

    }


    @PostMapping("/login")     //学生验证登录
    public ResponseEntity<?> login(String serialNumber,String password){
       /* if(studentDAO.existsBySerialNumberAndPassword(serialNumber,password)){
            return new ResponseEntity<>(HttpStatus.OK);
        }else{
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }*/

       if(userService.checkStudentPassword(serialNumber, password)){
           return new ResponseEntity<>(HttpStatus.OK);
       }else{
           return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
       }

    }



    @DeleteMapping("/delete")  //删除学生
    public ResponseEntity<String> delete(String serialNumber){  //如果不是复杂的对象之类的就可以不用@RequestBody
        if(!studentDAO.existsBySerialNumber(serialNumber)){
            return new ResponseEntity<>("该学生不存在", HttpStatus.BAD_REQUEST);//参数有误
        }else{
            studentDAO.deleteBySerialNumber(serialNumber);
            return new ResponseEntity<>("删除成功",HttpStatus.OK);
        }
    }

    @GetMapping("/findOne")        //根据学号查一个学生
    public ResponseEntity<?> findOne(String serialNumber){
        if(studentDAO.existsBySerialNumber(serialNumber))
            return new ResponseEntity<>(studentDAO.findStudentBySerialNumber(serialNumber),HttpStatus.OK);
        return new ResponseEntity<>("该学生不存在",HttpStatus.BAD_REQUEST);
    }

    @GetMapping("/findAll")      //查出（显示）所有学生信息
    public ResponseEntity<List<Student>> findAll(){
       return new ResponseEntity<>(studentDAO.findAll(),HttpStatus.OK) ;
    }
}
